package portal.manager.tracker;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;

import portal.manager.servlet.HttpContextProxy;
import portal.manager.servlet.PortalManagerServlet;

/**
 * 
 * @author Sorrentino
 *
 */
public class HttpServiceTracker extends ServiceTracker {

	private List<HttpService> httpServices = new ArrayList<HttpService>();
	
	public HttpServiceTracker(BundleContext context)  {
		super(context, HttpService.class.getName(), null /* Customizer */);
	}

	private void checkAndCall() {
		if (httpServices.isEmpty()) {
			return;
		}
		try {
			for (HttpService httpService : httpServices) {

				System.out.printf( "httpservice %s\n", httpService.toString());
				addServiceInternal(httpService);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public Object addingService(ServiceReference reference) {
		Object service = super.addingService(reference);
		if (service instanceof HttpService) {
			addHttpService((HttpService) service);
		}
		return service;
	}

	private void addHttpService(HttpService addingService) {
		this.httpServices.add(addingService);
		checkAndCall();

	}

	/**
	 * 
	 * @param httpService
	 * @throws Exception
	 */
	public void addServiceInternal(HttpService httpService) throws Exception {
	
		//BundleEntryHttpContext commonContext = new BundleEntryHttpContext(context.getBundle(), "/hello");
		HttpContext commonContext = httpService.createDefaultHttpContext();

		Dictionary<String, String> initparams = new Hashtable<String, String>(2);
		initparams.put("servlet-name", "portal");
		initparams.put("load-on-startup", "1");
		
		httpService.registerResources( "/", "/WebContent", new HttpContextProxy(commonContext));

		httpService.registerServlet("/osgip", new PortalManagerServlet(super.context), initparams, new HttpContextProxy(commonContext) );

		Dictionary<String, String> jsoninitparams = new Hashtable<String, String>(1);
		jsoninitparams.put("gzip_threshold", "200");

		javax.servlet.Servlet jsonrpcservlet = new portal.manager.servlet.JSONRPCServlet();
		
		httpService.registerServlet("/JSON-RPC", jsonrpcservlet, jsoninitparams, commonContext);
		
		
}

	

}
